# -*- coding: utf-8 -*-

'''
Created on 26/11/2011

@author: Luis M. Ugalde
www.forondarena.net

Copyright © 2011 Luis M. Ugalde
Licensed under the terms of the MIT License
(see LICENSE file for details)

This software can't be considered to be even in Alpha state. It still needs a lot of work.
'''


from . import abstractreader
import zmq
from readers.readerexception import ReaderException


class ReaderFile(abstractreader.AbstractReader):
    '''
    Class to read from regular files, line by line.
    This reader will signal parsers when the file ends with a special "END" message. 
    '''


    def __init__(self):
        print self.__class__.__name__ + ": ReaderFile instance created"
        abstractreader.AbstractReader.__init__(self)

        
    def setSource(self, srcfilename = ""):
        '''
        The source for a file reader is  a regular log file.
        A ReaderFile assumes that the file ends sometime.
        '''
        
        self.filename = srcfilename


    def connectSources(self):
        '''
        Open the file set with setSource
        '''

        print "{}: Opening file for reading: {}".format(self.__class__.__name__, self.filename)
        try:
            self.file = open(self.filename, 'r')
        except IOError:
            tmpstr= 'Cant open ' + self.filename + ' make sure it is defined in the config file '
            raise ReaderException(tmpstr)


    def closeSources(self):
        '''
        Close the file set with setSource
        '''

        print "{}: Closing the source: {}".format(self.__class__.__name__, self.filename)
        self.file.close()


    def getLines(self):
        '''
        Read lines from file
        Send a special "END" line when the file ends to notify parsers.
        This method must detect when a file is rotated. It is not done yet.
        
        The reader won't send data until parsers are available. This is part of the push/pull socket definition.
        This definition also states that reaching the high water mark blocks the socket, so it should behave as desired.
        '''

        try:
            for line in self.file:
                self.readerbindsocket.send(line.rstrip())
                print "{}: Sent {}.".format(self.__class__.__name__, line.rstrip())
                
            self.readerbindnotifysocket.send('END')
            print "{}: Sent END.".format(self.__class__.__name__)
        except IOError:
            tmperror = "Unable to read from " + self.filename
            raise ReaderException(tmperror)
        finally:
            self.closeSources()
            self.closeBindReader()
            self.closeBindNotifyReader()
            self.closeContext()


if __name__ == '__main__':
    print "Please, do not run this"
